package com.edu.atams.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Data
@Component
@PropertySource(value = "classpath:application.yml")
@ConfigurationProperties(prefix = "wechat")
public class WeChatUtil {
    @Autowired
    RedisUtil redisUtil;

    @Autowired
    AsyncRequestUtil asyncRequestUtil;

    public String getOpenid(String code) {
        String result = HttpUtil.get(code2Session.replace("APPID", appId).replace("SECRET", secret).replace("JSCODE", code));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        return jsonObject.getStr("openid");
    }

    public String getAccessToken() {
        String access_token = "";
        // access_token 的有效期目前是7200秒,且有限用调用次数2000次，这里用缓存
        if (redisUtil.hasKey("wx_access_token")) {
            access_token = (String) redisUtil.get("wx_access_token");
        } else {
            String result = HttpUtil.get(access_token_url.replace("APPID", appId).replace("APPSECRET", secret));
            JSONObject jsonObject = JSONUtil.parseObj(result);
            access_token = jsonObject.getStr("access_token");
            if(StrUtil.isNotBlank(access_token)) redisUtil.set("wx_access_token", access_token, 7000);
        }
        return access_token;
    }

    public void sendHomeworkNotice(List<String> openids, Map<String, String> keyword) {
        // 只要用户有进行订阅模板，然后开发者用appid和secret获取自己的access_token,才能调用微信的api, 接着就是对有订阅的openid进行发送消息模板通知
        String accessToken = getAccessToken();

        // 设置发送调用api的参数
        JSONObject body = new JSONObject();
        body.set("template_id", notice_homework_id);
        body.set("page", voting_page);
        body.set("miniprogram_state", "developer");
        body.set("lang", "zh_HK");
        JSONObject json = new JSONObject();
        json.set("thing1", new JSONObject().set("value", keyword.get("title")));
        json.set("time3", new JSONObject().set("value", keyword.get("end_time")));
        json.set("thing4", new JSONObject().set("value", keyword.get("nickname")));
        body.set("data", json);

        String uniformSendUrl =  uniform_send.replace("ACCESS_TOKEN", accessToken);
        openids.forEach(openid -> {
            body.set("touser", openid);
            try {
                asyncRequestUtil.asyncPostRequest(uniformSendUrl, body.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void sendSchoolNotice(List<String> openids, Map<String, String> keyword) {
        // 只要用户有进行订阅模板，然后开发者用appid和secret获取自己的access_token,才能调用微信的api, 接着就是对有订阅的openid进行发送消息模板通知
        String accessToken = getAccessToken();

        // 设置发送调用api的参数
        JSONObject body = new JSONObject();
        body.set("template_id", notice_shoolNotice_id);
        body.set("page", voting_page);
        body.set("miniprogram_state", "developer");
        body.set("lang", "zh_HK");
        JSONObject json = new JSONObject();
        json.set("thing1", new JSONObject().set("value", keyword.get("type")));
        json.set("thing2", new JSONObject().set("value", keyword.get("title")));
        json.set("thing3", new JSONObject().set("value", "发布人："+keyword.get("nickname")));
        body.set("data", json);

        String uniformSendUrl =  uniform_send.replace("ACCESS_TOKEN", accessToken);
        openids.forEach(openid -> {
            body.set("touser", openid);
            try {
                asyncRequestUtil.asyncPostRequest(uniformSendUrl, body.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }


    @Value("${appid}")
    private String appId;

    @Value("${secret}")
    private String secret;

    @Value("${notice_homework_id}")
    private String notice_homework_id;
    @Value("${notice_shoolNotice_id}")
    private String notice_shoolNotice_id;

    @Value("${voting_page}")
    private String voting_page;

    private String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    private String code2Session = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
    private String uniform_send = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
}
